<?php
namespace Home\Controller;
use Think\Controller;
class FaultController extends Controller {
	public function index(){
		
    }
	public function fault_add(){
		
		$token = A('Token');
		$access_token = $token->index();
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";//生成提交接口连接

		$user = M('User');
		$condition['user_tel'] = $_POST['user_tel'];
		$user_arr = $user->where($condition)->field('username,user_room')->find();//根据电话号查找房间号与姓名
		
		if($user_arr){
			
			$fault = M('Fault');
			$fault->create();
			$fault->date = time();
			$result = $fault->add();//添加故障信息到故障表
			
			if($result){
				
				$contentText = $user_arr['username'].'['.$user_arr['user_room'].']'.'：'.$_POST['fault_type'];//生成d推送的内容
				$contentText = urlencode($contentText);//转码
				$a = array("content"=>"{$contentText}");
				$b = array("touser"=>"o9o4ExP3YotIiXU7acKb3s5LiQUY","msgtype"=>"text","text"=>$a);
				$c = array("touser"=>"o9o4ExOBXEHfxl8x8ncCIQLhxHCI","msgtype"=>"text","text"=>$a);
				$post = json_encode($b);
				$post = urldecode($post);//解码
				
				$post1 = json_encode($c);
				$post1 = urldecode($post1);//解码

				$api = A('Api');
				$api->https_request($url,$post);
				$api->https_request($url,$post1);
				$this->success('新增与推送成功', '/index.php/Home/');//设置成功后跳转页面的地址
				
			}else {
				//错误页面的默认跳转页面是返回前一页，通常不需要设置
				$this->error('新增失败');
			}
		}else{
			$this->error('此号码的用户并不存在，需要添加新的用户！','/index.php/Home/User/user_add/user_tel/'.$condition['user_tel'],3);
		}
	}
	public function fault_del(){
		
	}
	public function fault_up(){
		
	}
	public function fault_push($fromUsername){
		$fault = M('Fault');
		$condition['state'] = 0;
		$fault_arr = $fault->where($condition)->field('id,user_tel,fault_type')->select();
		
		$token = A('Token');
		$access_token = $token->index();
		
		$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=$access_token";
		$api = A('Api');
			
		$user = M('User');
		foreach ($fault_arr as $fault_select){
			
			$condition['user_tel'] = $fault_select['user_tel'];
			$user_arr = $user->where($condition)->field('username,user_room')->find();
			
			$contentText = $user_arr['username'].'['.$user_arr['user_room'].']'.'：'.$fault_select['fault_type'];
			$contentText = urlencode($contentText);//转码
			$a = array("content"=>"{$contentText}");
			$b = array("touser"=>"{$fromUsername}","msgtype"=>"text","text"=>$a);
			$post = json_encode($b);
			$post = urldecode($post);//解码
			$api->https_request($url,$post);
			$condition_up['id'] = $fault_select['id'];
			$data['state'] = 1;
			$fault->where($condition_up)->save($data);
		}
	}
	public function fault_push1(){
		$user = M('User');
		$condition['user_tel'] = '3310';
		$user_arr = $user->where($condition)->field('username,user_room')->find();
		print_r($user_arr);
	}
	
}